<template>
  <div class="backbox">
    <div class="login">
      <h1>{{ t('title') }}</h1>

      <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
        <el-form-item label="用户名登录" prop="username">
          <el-input v-model="ruleForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="userpwd">
          <el-input v-model="ruleForm.userpwd" type="password" autocomplete="off" placeholder="请输入密码" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)" style="margin-left:37px;" class="my-element>登录</el-button>
        </el-form-item>
      </el-form>
      <div style="display: flex;width: 150px; justify-content: space-evenly;margin-left: 255px;">
        <div @click="handleChange('zh')">中文</div>
        <div @click="handleChange('en')">English</div>
      </div>

    </div>
    <!-- 拖拽图片验证码 -->
    <div class="slideverify" v-show="isShowSlide">
      <verify @verify-success="sliderVerifySuccess"></verify>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Verify from "../components/SliderVerify.vue";
import { userLogin } from '../services/userService'
import { reactive, ref } from 'vue'

import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useMenuStore, useuserInfoStore } from '../stores/counter'
import routerConfig from '../router/config'
import { useI18n } from "vue-i18n";
const { t } = useI18n()

const handleChange = (value: any) => {
  localStorage.setItem("lang", value)
  window.location.reload(); // 刷新页面
}

// 是否显示拖拽图片验证组件
const isShowSlide = ref(false)

let $router = useRouter()
let $menuStore = useMenuStore()
let $userInfoStore = useuserInfoStore()
const ruleFormRef = ref<FormInstance>() //表单元素
const ruleForm = reactive({
  //数据
  userpwd: '',
  username: ''
})

const validateUsername = (rule: any, value: any, callback: any) => {
  if (value.length >= 4 && value.length <= 10) {
    callback()
  } else {
    callback(new Error('长度只能是4到10位'))
  }
  // if (!value) {
  //   return callback(new Error('Please input the age'))
  // }
  // setTimeout(() => {
  //   if (!Number.isInteger(value)) {
  //     callback(new Error('Please input digits'))
  //   } else {
  //     if (value < 18) {
  //       callback(new Error('Age must be greater than 18'))
  //     } else {
  //       callback()
  //     }
  //   }
  // }, 1000)
}

const rules = reactive<FormRules<typeof ruleForm>>({
  username: [{ validator: validateUsername, trigger: 'blur' }],
  userpwd: [
    { pattern: /^[a-z0-9]{6,12}$/i, message: '密码只能数字字母组成长度6到12位', trigger: 'blur' }
  ]
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  // @ts-ignore
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      // 进行拖拽验证
      isShowSlide.value = true
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const sliderVerifySuccess = async (times: number) => {
  console.log(`耗时${(times / 1000).toFixed(1)}s`);
  isShowSlide.value = false
  //此处的处理是：图片验证通过后
  let res = await userLogin({
    ...ruleForm
  })
  if (res.data.code == 200) {
    window.localStorage.setItem('token', res.data.token)
    window.localStorage.setItem('menuList', JSON.stringify(res.data.data.menuList))
    window.localStorage.setItem('routerList', JSON.stringify(res.data.data.routerList))
    window.localStorage.setItem('userinfo', JSON.stringify(res.data.userinfo))

    $userInfoStore.inituserinfo(res.data.userinfo)
    $menuStore.initList(res.data.data.menuList)
    console.log($menuStore.list);

    let routerList = res.data.data.routerList

    //清空路由
    $router.removeRoute('main')
    $router.addRoute('main', {
      path: '/main',
      name: 'main',
      component: routerConfig['main']
    })

    $router.addRoute('main', {
      //设置默认
      path: '',
      name: 'main1',
      component: routerConfig[routerList[0].com]
    })

    routerList.forEach((item: any) => {
      $router.addRoute('main', {
        path: '/main' + item.path,
        name: item.name,
        component: routerConfig[item.com]
      })
    })
    // console.log($router.getRoutes())
    //登陆成功
    $router.push('/main')
  } else {
    ElMessage(res.data.msg)
  }
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

</script>
<style>
.login {
  width: 650px;
  height: 450px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border-radius: 5px;
  background-color: #fff;
  padding: 40px 50px;
  box-shadow: #b8e5f8;
  box-sizing: border-box;
  background-image: url(https://img2.baidu.com/it/u=937268429,903831764&fm=253&fmt=auto&app=138&f=JPEG?w=100&h=100);
  background-repeat: no-repeat;
  background-size: 220px 220px;
  background-position: bottom left;
}

.login .el-form-item__content {
  width: 440px;
  display: flex;
  justify-content: space-between;
}

.login .el-button {
  width: 350px;
  height: 40px;
}

.login .el-input__inner {
  height: 35px;
}

.login h1 {
  text-align: center;
  margin-bottom: 50px;
  color: #1772f6;
}

.backbox {
  width: 100vw;
  height: 100vh;
  background-color: #b8e5f8;
  background-image: url(https://static.zhihu.com/heifetz/assets/sign_bg.47eec442.png);
}

/* 拖拽图片验证 */
.slideverify {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  box-shadow:
    7px 7px 12px rgba(6, 8, 0, .4),
    -7px -7px 12px rgba(255, 255, 255, .9);
  padding: 10px;
}

.my-element {
  display: inline-block;
  margin: 0 0.5rem;

  animation: bounce; /* referring directly to the animation's @keyframe declaration */
  animation-duration: 2s; /* don't forget to set a duration! */
}
</style>
